<?php
error_reporting(E_ALL);
session_start();

function getCurrentAction() {
	global $config;

	if(isset($_GET['action']) == true) {
		return $_GET['action'];
	}
	else {
		return $config['defaultaction'];
	}
}


include("config.php");
include("functions.php");
include("login.php");

require("model/database.php");
require("view/user.class.php");
require("view/stationsummary.class.php");
require("view/stationstable_query1.class.php");
require("view/stationstable_query2.class.php");

$database = new Database();
$database->databaseConnect();
include("view/map.class.php");

if(!isset($_SESSION['user'])) {
	$_SESSION['user'] = new User($database);
}
$user = $_SESSION['user'];

$stationtable1 = new StationtableQ1();
$stationtable2 = new StationtableQ2();
$stationsummary = new Stationsummary();

echo '<a href="index.php?action=stationtable1">Query 1<a><br/>';
echo '<a href="index.php?action=stationtable2">Query 2<a><br/>';
echo '<a href="index.php?action=map">Google Maps<a>';

if($user->getLevel() == 0) {
	switch(getCurrentAction()) {
		case "loginCheck";
			loginCheck($user);		
			break;
	}
}
else if($user->getLevel() > 0) {
	switch(getCurrentAction()) {
		case "stationtable1":
			$query = $database->select("SELECT s.stn, name, country, temp, AVG(prcp) FROM stations AS s, measurement AS m
			WHERE s.stn = m.stn
			AND m.date = CURDATE()
			GROUP BY s.stn
			HAVING MAX(temp) BETWEEN 20 AND 30
			AND AVG(prcp) BETWEEN 5 AND 10");
			$stationtable1->setData($query);
			$stationtable1->display();
			break;
		case "stationtable2":
			$query = $database->select("SELECT s.stn, name, country, s.latitude, AVG(temp) FROM stations AS s, measurement AS m
			WHERE s.stn = m.stn
			AND DATEDIFF(m.date, CURDATE()) <= 28
			GROUP BY s.stn
			HAVING s.latitude BETWEEN 15 AND 16
			AND AVG(temp) > 20");
			$stationtable2->setData($query);
			$stationtable2->display();
			break;
		case "stationsummary":
			if(!isset($_GET['history'])) {
				//default
				$history = 30;
			}
			else {
				$history = $_GET['history'];
			}
			$query = "SELECT s.stn, name, country, latitude ,longitude, elevation, 
					AVG(temp), AVG(dewp), AVG(stp), AVG(slp), AVG(visib), AVG(wdsp), AVG(prcp), 
					AVG(sndp), frshtt, AVG(cldc), AVG(wnddir)
					FROM stations AS s, measurement AS m 
					WHERE s.stn = ".$_GET["stn"]."
					AND DATEDIFF(m.date, CURDATE()) <= ".$history;
			$query = $database->select($query);
			$stationsummary->setData($query);
			$stationsummary->display();
			break;
		case "graph":
			$graph = new Graph();
			$graph->display();
			break;
		case "map":
			$map = new Map();
			$map->display();
			break;
		default:
		case "home":
			echo 'Welcome'.$user->getUsername();
			break;
	}
}
else {
	displayLogin();
}












?>